import {
  HttpException,
  HttpStatus,
  Injectable,
  NestMiddleware,
} from '@nestjs/common';
import { TokenService } from 'src/service/token.service';

@Injectable()
export class AuthMiddleware implements NestMiddleware {
  constructor(private readonly tokenService: TokenService) {}
  async use(req: any, res: any, next: () => void) {
    const Authorization = req.headers['authorization'];
    if (!Authorization) {
      throw new HttpException('没有token', HttpStatus.FORBIDDEN);
    }
    try {
      const res = await this.tokenService.decoded(Authorization);
      next();
      return;
    } catch (err) {
      throw new HttpException(err, HttpStatus.FORBIDDEN);
    }
  }
}
